/**
 * 
 */
package br.com.pim.action;

import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.actions.DispatchAction;

import br.com.pim.connection.ConnectionFactory;
import br.com.pim.dao.UsuarioDAO;
import br.com.pim.form.LoginForm;
import br.com.pim.model.UsuarioModel;
import br.com.pim.util.ConstantesGerais;

/**
 * @author douglas.peixoto
 * 
 */
public class LoginAction extends DispatchAction {

	public ActionForward logon(ActionMapping mapping, ActionForm form,
			HttpServletRequest req, HttpServletResponse resp){

		LoginForm usuarioForm = null;;
		Connection connection= null;
		boolean result = false;
			
				try {
		
						try {
							connection = new ConnectionFactory().getConnectionMySQL();
						} catch (SQLException e) {
							result = false;	
							e.getMessage();
						}
							usuarioForm = (LoginForm) form;
							UsuarioDAO usuario = new UsuarioDAO(connection);
							UsuarioModel usuarioLogado = null;
								try {
									usuarioLogado = usuario.logon(usuarioForm.getUsuario());
										
									if(usuarioLogado == null){
											ActionErrors errors = new ActionErrors();
											errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("DE"));
											super.saveErrors(req, errors);
											result = false;
											
											
										}
									else{
										usuarioForm.setUsuario(usuarioLogado);
										result = true;
									}
									
								} catch (SQLException e) {
									ActionErrors errors = new ActionErrors();
									errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage(ConstantesGerais.ERROR_GENERICO));
									super.saveErrors(req, errors);
									result = false;
								}
								
						
						
					
		
				} finally {
					try {
						connection.close();
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}if(result == true){
				return mapping.findForward(ConstantesGerais.SUCCESS);
				}else{
					ActionErrors errors = new ActionErrors();
					errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("ERRO"));
					super.saveErrors(req, errors);
					return mapping.findForward(ConstantesGerais.FAILURE);
				}
			}

	
	public ActionForward logoff(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
		request.getSession().invalidate();
		return mapping.getInputForward();
	}
}
